package com.auth.manage.rpc.face;

import com.alibaba.fastjson2.JSON;
import com.auth.manage.base.responce.BaseResponce;
import com.auth.manage.base.responce.ResponceCode;
import com.auth.manage.base.util.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Slf4j
@Aspect
public class RPCIfaceAspect {

    @Around("@annotation(com.auth.manage.rpc.face.RPCIface)")
    public Object process(ProceedingJoinPoint proceedingJoinPoint){
        // 打印接口耗时，入参出参，RPC参数校验
        // 1.打印方法名、入参出参
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = proceedingJoinPoint.getArgs();  // 参数值
        String methodName = method.getName();  // 方法名
        log.info("开始执行方法：方法名：{}， 参数：{}",methodName, JSON.toJSONString(args));
        // 2.RPC接口的参数校验
        for (Object arg : args) {
            try {
                BeanValidator.validateObject(arg);
            } catch (Exception e) {
                // todo 日志输出
            }
        }
        // 3.打印接口耗时
        StopWatch watch = new StopWatch();
        try {
            Object responce = proceedingJoinPoint.proceed();
            enrichObj(responce);  // 如果responce没有添加上状态码就进行添加
            log.info("方法执行完成，耗时：{}，响应内容：{}", watch.getTime(), responce);
            return responce;
        } catch (Throwable e) {
            // todo 日志输出
            // todo return BaseResponce.fail(e.getMessage())
            // todo enrichObj(responce);
            throw new RuntimeException(e);
        }

    }

    private void enrichObj(Object responce) {
        switch (responce){
            case BaseResponce baseResponce:
                // 响应成功但是没有设置响应状态码
                if (baseResponce.getSuccess()){
                    if (StringUtils.isEmpty(baseResponce.getResponceCode())){
                        baseResponce.setResponceCode(ResponceCode.SUCCESS.name());
                    }
                }else {
                    // 响应失败但是没有设置响应状态码
                    if (StringUtils.isEmpty(baseResponce.getResponceCode())){
                        baseResponce.setResponceCode(ResponceCode.BIZ_ERROR.name());
                    }
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + responce);
        }
    }
}
